<?php

declare(strict_types=1);

namespace App\Common\Command;

use App\Common\Service\PluginsService;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\Output;

/**
 * 插件管理
 */
class Plugins extends Command
{

    /**
     * @return void
     */
    protected function configure(): void
    {
        $this->setName("plugins")
            ->addArgument('handleType', Argument::REQUIRED, '操作类型：install => 安装, uninstall => 卸载')
            ->addArgument('name', Argument::REQUIRED, '插件名称')
            ->setDescription('SC插件管理, 例（安装Api文档）: php think plugins install ApiDoc ');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     */
    protected function execute(Input $input, Output $output): void
    {
        $name = $input->getArgument('name');
        $type = $input->getArgument('handleType');

        if (!$name) {
            $output->error("请输入卸载的插件名称");
            return;
        }

        try {
            match ($type){
                'install'   => $this->install($output, $name),
                'uninstall' => $this->uninstall($output, $name),
                default => $output->error('操作类型错误，请输入： install(安装) 或 uninstall(卸载)')
            };
        } catch (\Throwable $e) {
            $output->error($e->getMessage());
        }
    }

    /**
     * @param Output $output
     * @param string $name
     * @return void
     * @throws \Exception
     */
    private function install(Output $output, string $name): void
    {
        PluginsService::aop(false)->install($name);
        $output->highlight("$name 安装成功");
    }

    /**
     * @param Output $output
     * @param string $name
     * @return void
     */
    private function uninstall(Output $output, string $name): void
    {
        PluginsService::aop(false)->uninstall($name);
        $output->highlight("$name 卸载成功");
    }
}
